"""
SchedulerAI 简化API接口

提供基础项目调度优化服务
"""

import os
import time
from datetime import datetime
from typing import Any, Dict

# 异常类已在error_handlers中处理
from .scheduler_service import SchedulerService


class SchedulerAI:
    """SchedulerAI 简化API类"""

    def __init__(self):
        """初始化API"""
        self.scheduler = SchedulerService()
        self.version = "2.0.0"

    def get_version(self) -> Dict[str, str]:
        """获取版本信息"""
        return {
            "version": self.version,
            "name": "SchedulerAI Simplified",
            "description": "简化的施工进度优化引擎",
        }

    def schedule_project(
        self, csv_path: str, output_format: str = "json"
    ) -> Dict[str, Any]:
        """
        基础项目调度

        Args:
            csv_path: CSV项目文件路径
            output_format: 输出格式 ("json" 或 "detailed")

        Returns:
            调度结果字典
        """
        try:
            start_time = time.time()

            # 执行调度
            result = self.scheduler.create_optimized_schedule(csv_path)

            processing_time = time.time() - start_time

            if result.success:
                response = {
                    "success": True,
                    "makespan": result.makespan,
                    "task_count": len(result.schedule) if result.schedule else 0,
                    "processing_time": round(processing_time, 3),
                    "timestamp": datetime.now().isoformat(),
                }

                if output_format == "detailed":
                    response["schedule"] = result.schedule
                    response["project_summary"] = result.project_summary

                return response
            else:
                return {
                    "success": False,
                    "error": result.error,
                    "processing_time": round(processing_time, 3),
                    "timestamp": datetime.now().isoformat(),
                }

        except Exception as e:
            return {
                "success": False,
                "error": f"调度失败: {str(e)}",
                "timestamp": datetime.now().isoformat(),
            }

    def validate_csv(self, csv_path: str) -> Dict[str, Any]:
        """
        验证CSV文件格式

        Args:
            csv_path: CSV项目文件路径

        Returns:
            验证结果字典
        """
        try:
            import pandas as pd

            # 检查文件是否存在
            if not os.path.exists(csv_path):
                return {"success": False, "error": f"文件不存在: {csv_path}"}

            # 读取CSV文件
            df = pd.read_csv(csv_path, encoding="utf-8")

            # 检查必需列
            required_columns = ["ID", "名称", "工期", "前置任务"]
            missing_columns = [col for col in required_columns if col not in df.columns]

            # 基础统计
            stats = {"total_tasks": len(df), "columns": list(df.columns)}

            return {
                "success": len(missing_columns) == 0,
                "file_path": csv_path,
                "file_size": os.path.getsize(csv_path),
                "missing_columns": missing_columns,
                "available_columns": list(df.columns),
                "statistics": stats,
                "timestamp": datetime.now().isoformat(),
            }

        except Exception as e:
            return {
                "success": False,
                "error": f"CSV验证失败: {str(e)}",
                "timestamp": datetime.now().isoformat(),
            }


# 便捷函数
def create_api() -> SchedulerAI:
    """创建API实例"""
    return SchedulerAI()


# 全局API实例（单例模式）
_api_instance = None


def get_api() -> SchedulerAI:
    """获取全局API实例"""
    global _api_instance
    if _api_instance is None:
        _api_instance = SchedulerAI()
    return _api_instance
